package com.web.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.time.DateUtils;

/**
 * @author yang mail:admin@seejoke.com
 * @date 2015-9-3 上午01:16:02
 * @package com.fh.util
 */
public class WebUtil {

    private static SimpleDateFormat dayFmarter = new SimpleDateFormat("yyyy-MM-dd");
    private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd EE", Locale.CHINA);

    /* 将长整型数字转换为日期格式的字符串 */
    public static String convert2String(long time, String format) {
        if (time > 0l) {
            SimpleDateFormat sf = new SimpleDateFormat(format);
            Date date = new Date(time);
            return sf.format(date);
        }
        return "";
    }

    /* 将日期格式的字符串转换为长整型 */
    public static long convert2long(String date, String format) {
        try {
            SimpleDateFormat sf = new SimpleDateFormat(format);
            return sf.parse(date).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0l;
    }

    /**
     * 随机生成六位数验证码
     *
     * @return
     */
    public static int getRandomNum() {
        Random r = new Random();
        return r.nextInt(900000) + 100000;// (Math.random()*(999999-100000)+100000)
    }

    /**
     * 检测字符串是否不为空(null,"","null")
     *
     * @param s
     * @return 不为空则返回true，否则返回false
     */
    public static boolean notEmpty(String s) {
        return s != null && !"".equals(s) && !"null".equals(s);
    }

    /**
     * 检测字符串是否为空(null,"","null")
     *
     * @param s
     * @return 为空则返回true，不否则返回false
     */
    public static boolean isEmpty(String s) {
        return s == null || "".equals(s) || "null".equals(s);
    }

    /**
     * 字符串转换为字符串数组
     *
     * @param str        字符串
     * @param splitRegex 分隔符
     * @return
     */
    public static String[] str2StrArray(String str, String splitRegex) {
        if (isEmpty(str)) {
            return null;
        }
        return str.split(splitRegex);
    }

    /**
     * 用默认的分隔符(,)将字符串转换为字符串数组
     *
     * @param str 字符串
     * @return
     */
    public static String[] str2StrArray(String str) {
        return str2StrArray(str, ",\\s*");
    }

    /**
     * 按照yyyy-MM-dd HH:mm:ss的格式，日期转字符串
     *
     * @param date
     * @return yyyy-MM-dd HH:mm:ss
     */
    public static String date2Str(Date date) {
        return date2Str(date, "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 按照yyyy-MM-dd HH:mm:ss的格式，字符串转日期
     *
     * @param date
     * @return
     */
    public static Date str2Date(String date) {
        if (notEmpty(date)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                return sdf.parse(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return new Date();
        } else {
            return null;
        }
    }

    /**
     * 按照参数format的格式，日期转字符串
     *
     * @param date
     * @param format
     * @return
     */
    public static String date2Str(Date date, String format) {
        if (date != null) {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return sdf.format(date);
        } else {
            return "";
        }
    }

    /**
     * 把时间根据时、分、秒转换为时间段
     *
     * @param StrDate
     */
    public static String getTimes(String StrDate) {
        String resultTimes = "";

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        java.util.Date now;

        try {
            now = new Date();
            java.util.Date date = df.parse(StrDate);
            long times = now.getTime() - date.getTime();
            long day = times / (24 * 60 * 60 * 1000);
            long hour = (times / (60 * 60 * 1000) - day * 24);
            long min = ((times / (60 * 1000)) - day * 24 * 60 - hour * 60);
            long sec = (times / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);

            StringBuffer sb = new StringBuffer();
            // sb.append("发表于：");
            if (hour > 0) {
                sb.append(hour + "小时前");
            } else if (min > 0) {
                sb.append(min + "分钟前");
            } else {
                sb.append(sec + "秒前");
            }

            resultTimes = sb.toString();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return resultTimes;
    }


    public static void writeFile(String fileP, String content) {
        String filePath = String.valueOf(Thread.currentThread().getContextClassLoader().getResource("")) + "../../"; // 项目路径
        filePath = (filePath.trim() + fileP.trim()).substring(6).trim();
        if (filePath.indexOf(":") != 1) {
            filePath = File.separator + filePath;
        }
        try {
            OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(filePath), "utf-8");
            BufferedWriter writer = new BufferedWriter(write);
            writer.write(content);
            writer.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 验证邮箱
     *
     * @param email
     * @return
     */
    public static boolean checkEmail(String email) {
        boolean flag = false;
        try {
            String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
            Pattern regex = Pattern.compile(check);
            Matcher matcher = regex.matcher(email);
            flag = matcher.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }


    public static boolean checkMobileNumber(String mobileNumber) {
        boolean flag = false;
        try {
            Pattern regex = Pattern
                    .compile("^(((13[0-9])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8})|(0\\d{2}-\\d{8})|(0\\d{3}-\\d{7})$");
            Matcher matcher = regex.matcher(mobileNumber);
            flag = matcher.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    /**
     * 判断是否是数字
     *
     * @param str
     * @return
     */
    public static boolean isNumeric2(String str) {
        for (int i = str.length(); --i >= 0; ) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断对象为空
     *
     * @param object
     * @return
     */
    public static boolean isEmptyObject(Object object) {
        return (object == null) || (object == "");
    }

    public static Timestamp getDateTimestamp() {
        try {
            Timestamp d = new Timestamp(System.currentTimeMillis());
            return d;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getDateTime(String dateFormat) {
        try {
            Date today = new Date();
            DateFormat vFormat = new SimpleDateFormat(dateFormat);
            return vFormat.format(today);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取真实ip
     *
     * @param request
     * @return
     */
    public static String getRealIp(HttpServletRequest request) {
        String result = request.getHeader("x-forwarded-for");
        if ((result != null) && (result.trim().length() > 0)) {
            if (result.indexOf(".") == -1) {
                result = null;
            } else if (result.indexOf(",") != -1) {
                result = result.trim().replace("'", "");
                String[] temparyip = result.split(",");
                for (int i = 0; i < temparyip.length; ++i)
                    if ((isIPAddress(temparyip[i])) && (temparyip[i].substring(0, 3) != "10.")
                            && (temparyip[i].substring(0, 7) != "192.168")
                            && (temparyip[i].substring(0, 7) != "172.16."))
                        return temparyip[i];
            } else {
                if (isIPAddress(result)) {
                    return result;
                }
                result = null;
            }
        }
        if ((result == null) || (result.trim().length() == 0)) {
            result = request.getHeader("Proxy-Client-IP");
        }
        if ((result == null) || (result.trim().length() == 0)) {
            result = request.getRemoteAddr();
        }
        return result;
    }

    public static boolean isIPAddress(String str1) {
        return (str1 != null) && (str1.trim().length() >= 7) && (str1.trim().length() <= 15);
    }

    /**
     * 按照yyyy-MM-dd HH:mm:ss的格式，字符串转日期
     *
     * @param date
     * @return
     */
    public static Date str2Date(String date, String formart) {
        if (notEmpty(date)) {
            SimpleDateFormat sdf = new SimpleDateFormat(formart);
            try {
                return sdf.parse(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return new Date();
        } else {
            return null;
        }
    }

    /**
     * 隐藏ip
     *
     * @param ip
     * @return
     */
    public static String hideIp(String ip) {
        if (isEmpty(ip)) {
            return null;
        } else if (isIPAddress(ip)) {
            return ip.replaceAll("(\\d+\\.\\d+\\.\\d+\\.)\\d+", "$1*");
        } else {
            return null;
        }
    }

    /**
     * 隐藏邮箱
     *
     * @param email
     * @return
     */
    public static String hideEmail(String email) {
        if (isEmpty(email)) {
            return null;
        } else {
            String[] eml = email.split("@");
            int len = eml[0].length();
            if (len > 4) {
                len = 4;
            }
            String result = padRight(eml[0].substring(0, len), '*', eml[0].length()) + "@" + eml[1];
            return result;
        }
    }

    /* 补全 */
    public static String padRight(String t, char c, int n) {
        StringBuilder sb = new StringBuilder();
        sb.append(t);
        int g = n - t.length();
        for (int i = 0; i < g; i++)
            sb.append(c);
        return sb.toString();
    }

    /* cookie */
    public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }

    public static Cookie getCookieByName(HttpServletRequest request, String name) {
        Map cookieMap = ReadCookieMap(request);
        if (cookieMap.containsKey(name)) {
            Cookie cookie = (Cookie) cookieMap.get(name);
            return cookie;
        }
        return null;
    }

    private static Map<String, Cookie> ReadCookieMap(HttpServletRequest request) {
        Map cookieMap = new HashMap();
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                cookieMap.put(cookie.getName(), cookie);
            }
        }
        return cookieMap;
    }

    /**
     * @param str
     * @return 如果是符合网址格式的字符串, 返回<b>true</b>,否则为<b>false</b>
     */
    public static boolean isWebUrl(String str) {
        String regex = "http://(([a-zA-z0-9]|-){1,}\\.){1,}[a-zA-z0-9]{1,}-*";
        return match(regex, str);
    }


    public static int length(String str) {
        if (str == null || "".equals(str)) {
            return 0;
        }
        try {
            byte[] data = str.getBytes("GB2312");
            return data.length;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return 0;
        }
    }

    private static boolean match(String regex, String str) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        return matcher.matches();
    }

    /**
     * 缩略文本内容以省略号代替
     *
     * @param text      文本
     * @param maxLength 缩略后的最大长度，字节数
     * @return 被缩略的文本
     */
    public static String compressText(String text, int maxLength) {

        if (text.indexOf("—") != -1 && maxLength >= 30) {
            maxLength = maxLength - 2;
        }

        if (WebUtil.length(text) <= maxLength) {
            return text;
        }

        for (int i = 1; i < text.length(); i++) {
            String subText = text.substring(0, i + 1);
            if (WebUtil.length(subText) >= maxLength) {
                subText = text.substring(0, i);
                subText += "..";
                return subText;
            }
        }
        return text;
    }

    /**
     * 缩略文本内容指定长度不带省略号
     *
     * @param text      文本
     * @param maxLength 缩略后的最大长度，字节数
     * @return 被缩略的文本
     */
    public static String cutText(String text, int maxLength) {

        if (text.indexOf("—") != -1 && maxLength >= 30) {
            maxLength = maxLength - 2;
        }

        if (WebUtil.length(text) <= maxLength) {
            return text;
        }

        for (int i = 1; i < text.length(); i++) {
            String subText = text.substring(0, i + 1);
            if (WebUtil.length(subText) >= maxLength) {
                subText = text.substring(0, i);
                return subText;
            }
        }
        return text;
    }

    /* 获取32位主键 */
    public static String getUUid() {
        return UUID.randomUUID().toString().trim().replaceAll("-", "");
    }

    /**
     * 获取验证码(除去容易混淆的字符)
     *
     * @param length
     * @return
     */
    public static String getCode(int length) {
        String base = "1234567890";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; ++i) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 四舍五入
     *
     * @param d
     * @param i
     * @return
     */
    public static double formartDouble(double d, Integer i) {
        BigDecimal b = new BigDecimal(d);
        return b.setScale(i, RoundingMode.HALF_UP).doubleValue();
    }

    /* 时间格式化 */
    public static String getStringDate(Date date, String dataFormat) {
        SimpleDateFormat formatter = new SimpleDateFormat(dataFormat);
        // SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
        return formatter.format(date);
    }

    /**
     * 获取上周一日期
     *
     * @param date
     * @return
     */
    public static Date getLastWeekMonday(Date date) {
        Date a = DateUtils.addDays(date, -1);
        Calendar cal = Calendar.getInstance();
        cal.setTime(a);
        cal.add(Calendar.WEEK_OF_YEAR, -1);// 一周
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        return cal.getTime();
    }

    public static void main(String[] args) {
        // System.out.println(getLastWeekMonday(new Date()));
        WebUtil.getWeekdays(new Date());

    }

    /**
     * 获取两周内所有日期
     *
     * @param date
     * @return
     */
    public static Map<String, String> getWeekdays(Date date) {
        Map<String, String> dateMap = new HashMap<String, String>();
        Date a = DateUtils.addDays(date, -1);
        Calendar cal = Calendar.getInstance();
        cal.setTime(a);
        cal.add(Calendar.WEEK_OF_YEAR, -1);// 一周
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        for (int i = 0; i < 14; i++) {
            dateMap.put(dayFmarter.format(cal.getTime()), dateFormat.format(cal.getTime()));
            // System.out.println(dayFmarter.format(cal.getTime()) + "--" +
            // dateFormat.format(cal.getTime()));
            cal.add(Calendar.DATE, 1);
        }
        return dateMap;
    }
}
